package org.chen.spring.cloud.finchley.zuul.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;

import static org.springframework.cloud.netflix.zuul.filters.support.FilterConstants.POST_TYPE;

/**
 * @author chensj
 * @date 2020-02-09 07:51
 */
public class PostFilter extends ZuulFilter {
  private static final Logger log = LoggerFactory.getLogger(PostFilter.class);

  @Override
  public String filterType() {
    return POST_TYPE;
  }

  @Override
  public int filterOrder() {
    return 0;
  }

  @Override
  public boolean shouldFilter() {
    return true;
  }

  @Override
  public Object run() throws ZuulException {
    log.info("进入{} 过滤器，开始处理全部过滤结果", getClass());
    // 从RequestContext获取Context
    RequestContext ctx = RequestContext.getCurrentContext();
    // 处理返回中文乱码问题
    ctx.getResponse().setCharacterEncoding("UTF-8");
    // 获取处理结果responseBody
    String responseBody = ctx.getResponseBody();
    if (StringUtils.isEmpty(responseBody)) {
      // 设定返回状态码
      ctx.setResponseStatusCode(500);
      // 替换响应报文
      ctx.setResponseBody(responseBody);
    }
    return null;
  }
}
